﻿#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void CountSort(int* a, int n)
{
	int max = a[0], min = a[0];
	for (int i = 0; i < n; i++)
	{
		if (a[i] > max)
			max = a[i];
		if (a[i] < min)
			min = a[i];
	}

	int range = max - min + 1;
	int* CountA = (int*)calloc(range, sizeof(int));
	if (CountA == NULL)
	{
		perror("Malloc fail");
	}
	//计数
	for (int i = 0; i < n; i++)
	{
		CountA[a[i] - min]++;
	}
	//排序
	int j = 0;
	for (int i = 0; i < range; i++)
	{
		while (CountA[i]--)
		{
			a[j++] = i + min;
		}
	}
	free(CountA);
}

void print(int* a, int n)
{
	for (int i = 0; i < n; i++)
	{
		printf("%d ", a[i]);
	}

}

int main()
{
	int a[] = {1,3,2,5,5,-2,-4,8,1};
	int n = sizeof(a) / sizeof(int);
	CountSort(a, n);
	print(a, n);
	return 0;
}